//Given an integer array nums that may contain duplicates, return all possible s
//ubsets (the power set). 
//
// The solution set must not contain duplicate subsets. Return the solution in a
//ny order. 
//
// 
// Example 1: 
// Input: nums = [1,2,2]
//Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
// Example 2: 
// Input: nums = [0]
//Output: [[],[0]]
// 
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 10 
// -10 <= nums[i] <= 10 
// 
// Related Topics 数组 回溯算法 
// 👍 584 👎 0

package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

 class P90SubsetsIi {
    public static void main(String[] args) {
        Solution solution = new P90SubsetsIi().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        List<List<Integer>> res = new ArrayList<>();

        public List<List<Integer>> subsetsWithDup(int[] nums) {

            int len = nums.length;
            Arrays.sort(nums);
            for (int i = 0; i <= len; i++) {
                visited = new boolean[nums.length];
                subsets(nums, 0, i, new ArrayList<>());
            }
            return res;
        }
        boolean[] visited;
        private void subsets(int[] arr, int start, int k, ArrayList<Integer> list) {
            if (k == 0) {
                res.add(new ArrayList<>(list));
                return;
            }
            for (int i = start; i < arr.length; i++) {
                if (i > 0 && arr[i] == arr[i - 1] && !visited[i - 1]) {
                    continue;
                }
                list.add(arr[i]);
                visited[i] = true;
                subsets(arr, i + 1, k - 1, list);
                list.remove(list.size() - 1);
                visited[i] = false;
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}